// 导入数据库模块
const db = require('../db/index')

// 工具类
const ResVo = require('../class/ResVo')
const Utils = require('../utils')

// ** ---------- api 处理逻辑 ---------- **
// 获取菜单权限 - 根据不同角色获取
const getMenu = async (req, res) => {
  try {
    // 1、根据 token 获取 登录用户的信息
    const { userId } = req.auth

    // 2、根据 用户主键 获取用户的角色,再依据角色获取菜单数据

    const { roleId, roleKey } = await getRoleByUserId(userId)

    if (roleKey === 'admin') {
      const menuList = await getMenuOfAdmin()
      return res.send(ResVo.setData(menuList))
    }
    // else {
    //   // 其他根据key进行菜单权限设置
    //   const menuList = await getMenuOfRole(roleId)
    //   return res.send(ResVo.setData(menuList))
    // }
  } catch (err) {
    // 如果getMenuOfAdmin出错，处理错误或返回错误信息给客户端
    console.error('Error fetching admin menu:', err)
    return res.send(ResVo.err(err, 500))
  }
}

// ** ---------- api 处理逻辑 End---------- **

// ** ---------- func ---------- **

// 获取角色信息 by user_id
async function getRoleByUserId(userId) {
  const sql = `select r.role_id,r.role_key,r.role_name 
  from sys_user as u 
  join sys_user_role as ur on ur.user_id = u.user_id
  join sys_role as r on r.role_id = ur.user_id
  where u.user_id = ?`
  try {
    const [results] = await db.query(sql, [userId])
    const transformedResults = Utils.transformedResults(results)
    let roleInfo = {}
    transformedResults.length > 0
      ? (roleInfo = transformedResults[0])
      : (roleInfo = { roleId: null, roleKey: '', roleName: '' })
    return roleInfo
  } catch (err) {
    console.warn(err)
  }
}

// 管理员的菜单权限
async function getMenuOfAdmin() {
  try {
    const sql = `select id, parent_id,name,path,redirect,component,icon,title,active_menu,is_link,is_hide,
   is_full,is_affix,is_keep_alive,sort,roles,type from sys_menu order by parent_id, sort`

    const [results] = await db.query(sql)

    // 特殊处理 具有特殊key的
    const transformedResults = Utils.transformedResultsSpeKey(results, 'roles')

    // 将查询的菜单数据，按照menu_id 和 parent_id 的关系，处理成 父子嵌套结构
    const convertedMenuData = convertMenuData(transformedResults)
    // 返回平铺和树形结构
    const data = {
      list: transformedResults, // 平铺的数据 - 菜单使用
      tree: convertedMenuData // 树形数据 - 路由使用
    }

    return data
  } catch (err) {
    console.warn(err)
  }
}

// 其他角色的菜单权限
function getMenuOfRole(roleId) {
  const sql = `select id, parent_id,name,path,redirect,component,icon,title,active_menu,is_link,is_hide,
  is_full,is_affix,is_keep_alive,sort,roles,type from sys_menu role_id order by parent_id, sort`

  db.query(sql, (err, result) => {})
}

// Meta 类
class Meta {
  constructor(data) {
    this.icon = data.icon
    this.title = data.title
    this.isLink = data.isLink
    this.isHide = !!data.isHide
    this.isFull = !!data.isFull
    this.isAffix = !!data.isAffix
    this.isKeepAlive = !!data.isKeepAlive
    this.roles = data.roles
  }
}

// 嵌套路由处理
function convertMenuData(list) {
  const result = []
  const menuMap = new Map()

  list.forEach((item) => {
    menuMap.set(item.id, {
      id: item.id,
      parentId: item.parentId,
      name: item.name,
      path: item.path,
      redirect: item.redirect,
      component: item.component,
      displayOrder: item.displayOrder,
      type: item.type,
      meta: new Meta(item),
      children: []
    })
  })

  // 递归优化子菜单优化
  const buildMenu = (parentId) => {
    const menuItems = []
    menuMap.forEach((menuItem) => {
      if (menuItem.parentId === parentId) {
        menuItem.children = buildMenu(menuItem.id)
        menuItems.push(menuItem)
      }
    })
    return menuItems
  }

  result.push(...buildMenu(null))

  return result
}

// ** ---------- func End---------- **

module.exports = {
  getMenu,
  Meta,
  convertMenuData
}
